package com.jhs.demo.rxandroid.http;


import com.jhs.demo.MyApp;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wangqi on 2018/8/24.
 */

public class ServiceManager {

    public static ServiceManager getInstance() {
        synchronized (ServiceManager.class) {
            if (INSTANCE == null) {
                INSTANCE = new ServiceManager();
            }
        }
        return INSTANCE;
    }

    private static ServiceManager INSTANCE;

    //超时时间
    private static final int DEFAULT_OUT_TIME = 10;
    private static final int DEFAULT_READ_OUT_TIME = 10;

    //Retrofit实例
    private Retrofit mRetrofit;

    private ServiceManager() {
        //初始化OKHttpClient
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(DEFAULT_OUT_TIME, TimeUnit.SECONDS);
        builder.readTimeout(DEFAULT_READ_OUT_TIME, TimeUnit.SECONDS);

        //拦截器
        HttpCommonInterceptor interceptor = new HttpCommonInterceptor();
        builder.addInterceptor(interceptor);

        mRetrofit = new Retrofit.Builder()
                .client(builder.build())
                .baseUrl(MyApp.BASE_URL)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public <T> T creat(Class<T> service) {
        return mRetrofit.create(service);
    }
}
